package my.sample.channel.datagram;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Arrays;
import java.util.Iterator;

public class ServerReject {

	boolean loop;
	private ByteBuffer receiveBuff = null;

	public ServerReject() {
		loop = true;

		this.receiveBuff = ByteBuffer.allocate(65536);
		this.receiveBuff.order(ByteOrder.BIG_ENDIAN);
	}

	public static void main(String[] args) {

		ServerReject server = new ServerReject();
		server.init(Integer.parseInt(args[0]));

	}

	private void init(int port) {

		try {
			
			
			ServerSocket server = new ServerSocket(port);
			
			Selector localSelector = Selector.open();
			DatagramChannel localDatagramChannel = DatagramChannel.open();
			localDatagramChannel.configureBlocking(false);
			localDatagramChannel.socket().bind(new InetSocketAddress(5555));
			localDatagramChannel.socket().setReceiveBufferSize(131071);

			localDatagramChannel.register(localSelector, 1);
			byte[] nameString = new byte[3];

			while (loop) {
				try {
					if (localSelector.select(2000L) == 0) {
						System.out.print(".");
					} else {
						Iterator localIterator = localSelector.selectedKeys().iterator();

						while (localIterator.hasNext()) {
							try {
								SelectionKey localSelectionKey = (SelectionKey) localIterator.next();

								if ((localSelectionKey.isValid()) && (localSelectionKey.isReadable())) {

									DatagramChannel localDatagramChannel1 = (DatagramChannel) localSelectionKey.channel();
									this.receiveBuff.clear();
									
									localDatagramChannel1.receive(this.receiveBuff);
									System.out.println("received data : " + Arrays.toString(receiveBuff.array()));
									this.receiveBuff.flip();
									this.receiveBuff.get(nameString, 0, 3);
									int value = this.receiveBuff.getInt();
									
									System.out.println(new String(nameString) + " : " + value);
									
									receiveBuff.limit();
									
//									System.out.print(receiveBuff.limit());
								}
							} catch (Exception loopException) {
//								logger.error("Exception in Key iteration", loopException);
								loopException.printStackTrace();
							}
						}

						localSelector.selectedKeys().clear();
					}
				} catch (Exception loopException2) {
//					logger.error("Exception in isPost loop", loopException2);
					loopException2.printStackTrace();
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (ClosedChannelException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
